package controllers;

import java.util.ArrayList;
import java.util.List;

import com.ning.http.client.Request;

import models.Dream;
import models.Keyword;
import models.User;
import play.mvc.Controller;
import play.i18n.Messages;
import play.data.validation.Validation;
import play.data.validation.Valid;

public class Dreams extends Controller {
    public static void index() {
        List<Dream> dreams = models.Dream.all().fetch();
        renderJSON(dreams);
    }

    public static void create(@Valid Dream entity) {
    	User user = User.find("byId", session.get("userId")).first();
    	Dream dream = new Dream();
    	dream.description = entity.description;
    	dream.price = entity.price;
    	dream.user = user;
    	
    	if(dream.save() != null){
    		renderJSON("{\"response\": \"ok\"}");
		} else {
			renderJSON("{\"response\": \"nok\"}");
		}
    	
    }

    // Return a specific dream by it's id...
    public static void show(java.lang.Long id) {
        Dream entity = Dream.findById(id);
        renderJSON(entity);
    }

    public static void edit(java.lang.Long id) {
        Dream entity = Dream.findById(id);
        render(entity);
    }

    public static void delete(java.lang.Long id) {
        Dream entity = Dream.findById(id);
        entity.delete();
        index();
    }
    
    public static void save(@Valid Dream entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("scaffold.validation"));
            render("@create", entity);
        }
        entity.save();
        flash.success(Messages.get("scaffold.created", "Dream"));
        index();
    }

    public static void update(@Valid Dream entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("scaffold.validation"));
            render("@edit", entity);
        }
        
        entity = entity.merge();
        
        entity.save();
        flash.success(Messages.get("scaffold.updated", "Dream"));
        index();
    }
    
    public static void indexByKeyword(List<String> keywords){
    	List<Dream> allDreams = Dream.findAll();
    	List<Keyword> keys = new ArrayList<Keyword>();
    	for (String key : keywords) {
    		List<Keyword> k = Keyword.find("byValue", key).fetch();
    		keys.addAll(k);
		}
    	
    	List<Dream> indexedDreams = new ArrayList<Dream>();
    	for (Keyword key : keys) {
    		for (Dream dream : allDreams) {
    			if(dream.keywords.contains(key)){
    				indexedDreams.add(dream);
    			}
    		}
		}
    	
    	renderJSON(indexedDreams);
    }
}
